// components/xcx-bar/xcx-bar.ts
import {
  placeholder,
  findOptionText,
} from '../../utils/tools'
import {
  regExp
} from '../../utils/regExp'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    config: {
      type: Object,
      value: {}
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    formConfig: {
      name: {
        type: 'text',
        label: '企业名称',
        value: '',
        maxlength: '',
        formLabelWidth: '',
        errMsg: '',
        required: '',
        validator: (context: TLooseObj) => baseValidator(context, 'formConfig', 'name')
      },
      code: {
        type: 'text',
        label: '统一社会信用代码',
        value: '',
        maxlength: '18',
        formLabelWidth: '',
        errMsg: '',
        required: ''
      },
      paperType: {
        type: 'select',
        label: '证件类型',
        options: [
          { id: 1, value: "SF", text: "身份证" },
          { id: 2, value: "HK", text: "户口簿" },
          { id: 3, value: "HZ", text: "护照/华侨护照" },
          { id: 4, value: "JR", text: "军人证" },
          { id: 5, value: "GA", text: "港澳台居民身份证" },
          { id: 6, value: "WF", text: "外国人永久居留身份证" },
          { id: 7, value: "TW", text: "台湾居民来往大陆通行证" },
          { id: 8, value: "WJ", text: "武警身份证" },
          { id: 9, value: "BM", text: "边民出入境通行证" },
          { id: 10, value: "QT", text: "其他证件" }
        ],
        value: '',
        formLabelWidth: '',
        errMsg: '',
        required: ''
      },
      isYouself: {
        type: 'switch',
        label: '是否为法定代表人本人办理',
        value: '',
        formLabelWidth: '16em',
        errMsg: '',
        required: ''
      },
      openingBankProvince: {
        type: 'cascade',
        label: '开户行省份',
        formLabelWidth: '',
        cascade: [
          {
            value: '',
            disabled: false,
            label: '开户行省份',
            options: [
              { id: 1, value: "SF", text: "身份证" },
              { id: 2, value: "HK", text: "户口簿" },
              { id: 3, value: "HZ", text: "护照/华侨护照" }
            ],
            // options: getPickerOptions('custType'),
            errMsg: '',
            // validator: (context: TLooseObj) => cascadeValidator(context, 'formConfig', 'job', 0)
          },
          {
            value: '',
            label: '开户行城市',
            disabled: true,
            options: [
              { id: 7, value: "TW", text: "台湾居民来往大陆通行证" },
              { id: 8, value: "WJ", text: "武警身份证" },
              { id: 9, value: "BM", text: "边民出入境通行证" },
              { id: 10, value: "QT", text: "其他证件" }
            ],
            // options: getPickerOptions('custType'),
            errMsg: '',
            // 真实的数据是动态获取的，为了快速调试，没有造真实的数据
            // validator: (context: TLooseObj) => cascadeValidator(context,   'formConfig', 'job', 1)
          }
        ]
      }
    },
    // 滚轮选项弹窗配置，所有滚轮选项复用
    pickerConfig: {
      // 处于激活状态的滚轮选择框
      activeKey: 'custType',
      // 级联选项索引序号
      cascadeIndex: '',
      // 控制选项弹窗的显隐
      visible: false,
    }
  },
  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      // this.setData({ formConfig: this.properties.config})
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 同步视图数据到模型
    viewToModel(event: WechatMiniprogram.CustomEvent) {
      // console.log(event);
      const field = event.currentTarget.dataset.field
      const { formConfig } = this.data as TLooseObj
      const type = formConfig[field].type

      if (type === "select") {
        const { value: item } = event.detail
        // console.log({ item });
        formConfig[field].value = item.value
      } else if (type === "cascade") {
        const { value: item } = event.detail
        const len = formConfig[field].cascade.length
        const cascadeIndex = event.currentTarget.dataset.cascadeIndex
        formConfig[field].cascade[cascadeIndex].value = item.value

        // 清空及禁用当前层级下一层级之后的级联选项
        for (let i = cascadeIndex + 1; i < len; i++) {
          formConfig[field].cascade[i].value = ''
          formConfig[field].cascade[i].disabled = true
        }

        // 不是最后一项的话，设置当前层级的下一层级可选以及选项列表
        if ((cascadeIndex + 1) < len) {
          formConfig[field].cascade[cascadeIndex + 1].disabled = false
          formConfig[field].cascade[cascadeIndex + 1].options = []
        }
      } else {
        formConfig[field].value = event.detail
      }
      this.setData({ formConfig })
      // console.log(formConfig)
    },
    // 触发滚轮选择弹窗显隐和表单项校验
    handleTriggerPicker(e: WechatMiniprogram.CustomEvent) {
      const { field, visible, cascadeIndex } = e.currentTarget.dataset
      const { formConfig, pickerConfig } = this.data as TLooseObj
      // console.log({ field, cascadeIndex, visible })
      pickerConfig.visible = visible
      pickerConfig.activeKey = field
      pickerConfig.cascadeIndex = cascadeIndex

      this.setData({ pickerConfig }, () => {
        // console.log(formConfig[field].type)
        if (['select', 'cascade'].includes(formConfig[field].type)) {
          // picker打开时,设置默认选中项
          if (visible) {
            this.setPickerDefaultIndex(formConfig, field, cascadeIdex)
          } else {
            // 关闭时触发选项校验
            this.triggerFormItemValidate(e)
          }
        }
      })
    },
    /**
     * 设置选项框打开时的默认选中项
     * @param formConfig   表单配置对象
     * @param field        表单字段名
     * @param cascadeIndex 级联层级序号
     */
    setPickerDefaultIndex(formConfig: TLooseObj, field: string, cascadeIndex: number) {
      let defaultIndex = 0
      const picker = this.selectComponent("#picker")
      const type = formConfig[field].type

      if (type === 'select') {
        defaultIndex = findOptionIndex(formConfig[field].options, formConfig[field].value)
      } else if (type === 'cascade') {
        const item = formConfig[field].cascade[cascadeIndex]
        defaultIndex = findOptionIndex(item.options, item.value)
      }

      // 找到此选项，设置默认选中
      if (defaultIndex !== -1) {
        picker.setColumnIndex(0, defaultIndex)
      }
    },
    // 处理滚轮选择确认事件
    handlePickerConfirm(event: WechatMiniprogram.CustomEvent) {
      this.viewToModel(event)
      // 关闭picker弹窗并触发表单项校验
      this.handleTriggerPicker(event)
    },
    /**
      * 表单项校验
      * @param context  Page对象上下文
      * @param formKey  表单字段名
      * @param field    表单项字段名
      */
    baseValidator(context: TLooseObj, formKey: string, field: string) {
      const { [formKey]: baseFormConfig } = context.data
      // console.log(baseFormConfig[field]);
      const { value, label, reg = '' } = baseFormConfig[field]
      // 空值判断
      if (`${value}`.trim() === '') {
        baseFormConfig[field].errMsg = `${label}不能为空`
        context.setData({ [formKey]: baseFormConfig })
        return false
      }
      
      // 正则校验--直接传正则表达式,值不正确
      if (reg && !regExp[reg].rule.test(value)) {
       baseFormConfig[field].errMsg = `${label}输入不正确`
       context.setData({ [formKey]: baseFormConfig })
       return false
      }
      
      baseFormConfig[field].errMsg = ''
      context.setData({ [formKey]: baseFormConfig })
      return true
    },
    // 表单失焦时触发校验
    // 调用表单项的validator方法，formConfig[field]?.validator(this)，完成表单项的校验
    triggerFormItemValidate(event: TLooseObj) {
      // console.log(event)
      const field = event.currentTarget.dataset.field
      const cascadeIndex = event.currentTarget.dataset.cascadeIndex
      const { formConfig } = this.data as TLooseObj
      const type = formConfig[field].type
  
      // 执行表单项配置的校验规则
      if (type === 'cascade') {
        const enable = formConfig[field].cascade[cascadeIndex].disabled === false
        // 当前层级可选时，才进行表单校验
        enable && formConfig[field].cascade[cascadeIndex]?.validator(this)
      } else {
        if (formConfig[field] && formConfig[field].validator) {
          formConfig[field].validator(this)
        } else {
          console.log(formConfig[field])
        } 
      }
    },
    // 表单提交时触发校验
    formValidate() {
      const { formConfig } = this.data as TLooseObj;
      const isAllPass = Object.keys(formConfig).map((key) => {
        const type = formConfig[key].type
        // 级联选择是个数组，每项都有校验器
        if (type === 'cascade') {
          return formConfig[key].cascade.map((item: TLooseObj) => item.validator(this)).every((isPass: boolean) => isPass)
        } else if (type === 'switch') {
          // 开关有默认选中项,无需校验
          return true
        } else {
          // console.log(formConfig[key])
          return formConfig[key].validator(this)
        }
      }).every((isPass: boolean) => isPass)
      console.log(isAllPass, '----isAllPass----')
      return isAllPass
    },
    // 获取表单数据的方法
    async getFormData() {
      const isAllPass = await this.formValidate()
      // 表单校验通过，遍历表单对象赋值
      if (isAllPass) {
        return Object.keys(formConfig).reduce((formData: TLooseObj, key: string) => {
          const type = formConfig[key].type
          if (type === 'cascade') {
            formData[key] = formConfig[key].cascade.map((item: TLooseObj) => item.value).join(',')
          } else {
            formData[key] = formConfig[key].value
          }
          return formData
        }, {})
      }
      return {}
    }
  }
})
